
package com.cicigodd.brick.plug.system.auth.operate;

import com.cicigodd.brick.plug.common.entity.LoginUser;
import com.cicigodd.brick.plug.common.exception.AuthException;
import com.cicigodd.brick.plug.common.utils.AuthUtil;
import com.cicigodd.brick.plug.jwt.api.JwtServiceContext;
import com.cicigodd.brick.plug.system.auth.api.AuthServiceApi;
import com.cicigodd.brick.plug.system.auth.api.SessionServiceApi;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 当前登陆用户的接口实现
 *
 * @author cicigodd
 * @date 2022/09/23 08:42:00
 */
@Component
public class AuthServiceImpl implements AuthServiceApi {

    @Resource
    private SessionServiceApi sessionServiceApi;

    @Override
    public String getToken() {
        return AuthUtil.getToken();
    }

    @Override
    public LoginUser getLoginUser() {

        // 获取用户的token
        String token = getToken();

        // 获取session中该token对应的用户
        LoginUser session = sessionServiceApi.getSession(token);

        // session为空抛出异常
        if (session == null) {
            throw new AuthException("当前登录会话过期，请重新登录");
        }

        return session;

    }


    @Override
    public boolean getSuperAdminFlag() {
        LoginUser loginUser = getLoginUser();
        return loginUser.getSuperAdmin();
    }

    @Override
    public boolean hasLogin() {

        // 获取用户的token
        String token = null;
        try {
            token = getToken();
        } catch (Exception e) {
            return false;
        }

        // 获取是否在会话中有
        return sessionServiceApi.haveSession(token);
    }

    @Override
    public void validateToken(String token) {
        try {
            // 1. 先校验jwt token本身是否有问题
            JwtServiceContext.me().validateTokenWithException(token);

            // 2. 判断session里是否有这个token
            LoginUser session = sessionServiceApi.getSession(token);
            if (session == null) {
                throw new AuthException("当前登录会话过期，请重新登录");
            }
        } catch (io.jsonwebtoken.JwtException jwtSelfException) {
            // 其他jwt解析错误
            throw new AuthException("当前登录会话过期，请重新登录");
        }
    }
}
